package edu.example.manage.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import edu.example.common.PageHelp;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;

/*操作方法封装*/
public class JDBCUtils {
    private static final ComboPooledDataSource CPDS;
    private static final QueryRunner RUN;
    private Connection connection;

    static {
        CPDS = new ComboPooledDataSource();
        RUN = new QueryRunner(CPDS);
    }

    private JDBCUtils() {}

    public static JDBCUtils createConnection() {
        try {
            JDBCUtils jdbcUtils = new JDBCUtils();
            jdbcUtils.connection = CPDS.getConnection();
            return jdbcUtils;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /*查询列表*/
    public <T> Object queryList(String sql, Class<T> clazz, Object... wheres) throws SQLException {
        BeanListHandler beanListHandler = new BeanListHandler(clazz);
        return RUN.query(sql, beanListHandler, wheres);
    }

    /*查询个数*/
    public Integer queryPageTotal(String sql) throws SQLException {
        return RUN.query(sql, new BeanHandler<>(PageHelp.class)).getPageTotal();
    }

    /*查询详情*/
    public <T> Object query(String sql, Class<T> clazz, Object... wheres) throws SQLException {
        BeanHandler beanHandler = new BeanHandler(clazz);
        return RUN.query(sql, beanHandler, wheres);
    }

    /*增删改*/
    public <T> int update(String sql, Object... params) throws SQLException {
        return RUN.update(sql, params);
    }
    public void setAutoCommit(boolean flag) throws SQLException {
        connection.setAutoCommit(flag);
    }
    public void commit() throws SQLException {
        connection.commit();
    }
    public void rollback() throws SQLException {
        connection.rollback();
    }
}
